package open.api.strategy.impl;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import open.api.config.payconfig.PayConfig;
import open.api.model.entity.Pay;
import open.api.model.entity.PayOrderResponse;
import open.api.model.entity.PayResponse;
import open.api.response.ResultData;
import open.api.strategy.PayStrategy;
import open.api.utils.RestTemplateUtil;
import open.api.utils.SignParamUtil;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: AlipayStrategyImpl
 * Package: open.api.strategy.impl
 * Description:
 *
 * @Author: @weixueshi
 * @Create: 2024/5/5 - 16:15
 * @Version: v1.0
 */
/**
 * 支付宝支付具体实现
 */
@Slf4j
@Component
public class AlipayStrategyImpl implements PayStrategy {
    @Override
    public ResultData pay(Pay pay) {
        //构造请求参数：说明，以下是属于真实生产环境的支付逻辑
        Map<String, String> params = new HashMap<>();
        params.put("pid", PayConfig.PID);
        params.put("type",PayConfig.TYPE_ALIPAY);
        params.put("out_trade_no",pay.getOrderId());
        params.put("notify_url",PayConfig.NOTIFY_URL);
        params.put("return_url",PayConfig.RETURN_URL);
        params.put("name",pay.getName());
        params.put("money",pay.getPrice());
        //参数过滤
        Map<String, String> paraFilter = SignParamUtil.paraFilter(params);
        //拼接后的字符串
        String linkString = SignParamUtil.createLinkString(paraFilter);
        //获得签名字符串
        String sign = SignParamUtil.sign(linkString, PayConfig.SECRET, PayConfig.INPUT_CHARSET);
        params.put("sign_type",PayConfig.SIGN_TYPE);
        params.put("sign",sign);
        //发起请求
        String response = RestTemplateUtil.post(PayConfig.URL, params);
        PayOrderResponse payOrderResponse = JSON.parseObject(response, PayOrderResponse.class);

        PayResponse payResponse = new PayResponse();
        payResponse.setPayUrl(payOrderResponse.getCode_url());
        payResponse.setTradeNo(payOrderResponse.getTrade_no());

        ResultData response1 = new ResultData();
        response1.setCode(payOrderResponse.getCode());
        response1.setMessage(payOrderResponse.getMsg());
        response1.setData(payResponse);
        return response1;
    }
}
